package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.db.api.*;
import com.tanhua.dubbo.mongo.api.RecommendUserApi;
import com.tanhua.dubbo.mongo.api.UserLikeApi;
import com.tanhua.dubbo.mongo.api.VisitorsApi;
import com.tanhua.model.db.*;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;

import com.tanhua.server.interceptor.UserHolder;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@Service
public class UsersService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //用户资料 - 读取
    public UserInfoVo findById(Long id) {

        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo userInfoVo = new UserInfoVo();

        //将userInfo中同名,同类型的属性,复制到userInfoVo中
        BeanUtil.copyProperties(userInfo, userInfoVo);

        //不同类型的属性 单独赋值
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    //
    public void updateUserInfo(UserInfo userInfo) {

        userInfoApi.updateUserInfo(userInfo);

    }

    //用户通用设置 - 读取
    public SettingsVo settings(Long userId, String mobile) {

        //创建SettingsVo对象
        SettingsVo vo = new SettingsVo();
        vo.setId(userId);
        vo.setPhone(mobile);

        //根据userId查询question,并赋值
        Question question = questionApi.findByUserId(userId);
        vo.setStrangerQuestion(question == null ? "" : question.getTxt());

        //根据userId查询settings,,并赋值
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }
        //返回值
        return vo;
    }

    //设置陌生人问题 - 保存
    public void saveQuestion(String content) {

        //1.获取userId
        Long userId = UserHolder.getUserId();

        //根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        //如果不存在,保存
        if (question == null) {
            question = new Question();
            //如果不存在,保存
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.saveQuestion(question);
        } else {
            //如果存在 更新
            question.setTxt(content);
            questionApi.updateQuestion(question);
        }


    }

    //通知设置 - 保存
    public void setting(Map map) {

        //1.获取userId
        Long userId = UserHolder.getUserId();


        //获取前端通知设置值
        //map :likeNotification,pinglunNotification,gonggaoNotification
        boolean likeNotification = (boolean) map.get("likeNotification");
        boolean pinglunNotification = (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (boolean) map.get("gonggaoNotification");

        //根据userid查询settings
        Settings settings = settingsApi.findByUserId(userId);

        //判断是否存在
        if (settings == null) {
            //保存:
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.saveSettings(settings);
        } else {
            //更新:
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.updateSettings(settings);
        }
    }


    //黑名单 - 翻页列表
    public PageResult blacklist(Integer page, Integer pagesize) {
        //获取userId
        Long userId = UserHolder.getUserId();
        PageResult result = blackListApi.blacklist(userId, page, pagesize);

        return result;

    }

    //黑名单 - 根据blackUserId移除
    public void deleteBlackUser(Long blackUserId) {

        //获取UserId;
        Long userId = UserHolder.getUserId();
        blackListApi.deleteBlackUser(userId, blackUserId);

    }


    //修改手机号 - 2 校验验证码
    public Boolean checkVerificationCode(String verificationCode) {

        String code = redisTemplate.opsForValue().get("verificationCode");

        if (code.isEmpty() || !code.equals(verificationCode)) {

            return false;
        }

        redisTemplate.delete("verificationCode");

        return true;
    }


    //修改手机号 - 3 保存
    public void updateMobile(String phone) {

        //1.获得用户id
        String mobile = UserHolder.getMobile();
        User user = userApi.findByMobile(mobile);
        user.setMobile(phone);
        userApi.updateMobile(user);

    }




    @DubboReference
    private UserLikeApi userLikeApi;

    //互相喜欢，喜欢，粉丝 - 统计
    public CountsVo counts() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //构造vo对象
        CountsVo countsVo = new CountsVo();
        //互相喜欢
        Integer count1 = Math.toIntExact(userLikeApi.likeEachOther(userId));
        countsVo.setEachLoveCount(count1);
        //喜欢
        Integer count2 = Math.toIntExact(userLikeApi.iLike(userId));
        countsVo.setLoveCount(count2);
        //粉丝
        Integer count3 = Math.toIntExact(userLikeApi.likeMe(userId));
        countsVo.setFanCount(count3);
        return countsVo;
    }
    /* 谁看过我 - 翻页列表
       1 互相关注
       2 我关注
       3 粉丝
       4 谁看过我*/
    public PageResult friends(Integer page, Integer pagesize, Integer type) {
        //剩下的查询 以后再实现
        PageResult pageResult = null;
        if (type == 1) {  //互相关注
            pageResult = eachLoveCount(page, pagesize, type);
            return pageResult;
        } else if (type == 2) { //我关注
            pageResult = loveCount(page, pagesize, type);
            return pageResult;
        } else if (type == 3) {  //3 粉丝
            pageResult = fanCount(page, pagesize, type);
            return pageResult;
        } else {//4 谁看过我
            pageResult = seeMe(page, pagesize, type);
            return pageResult;
        }
    }

    //3 粉丝
    private PageResult fanCount(Integer page, Integer pagesize, Integer type) {
        //粉丝  返回粉丝id
        List<Long> userLikes = userLikeApi.fanCount(page, pagesize, UserHolder.getUserId());

        //匹配度   分装成map
        Map<Long, RecommendUser> mapRecommendUser = recommendUserApi.fanCount(userLikes, UserHolder.getUserId());

        //粉丝的userInfo
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userLikes);

        //封装vo
        List<UserLikeListVo> userUserLikeListVoList = new ArrayList<>();

        if (mapRecommendUser == null || mapRecommendUser.size() <= 0) {
            for (Long userLike : userLikes) {
                UserLikeListVo userLikeListVo = new UserLikeListVo();
                UserInfo userInfo = byIds.get(userLike);
                BeanUtil.copyProperties(userInfo, userLikeListVo);
                userLikeListVo.setMatchRate(30);
                //UserLikeListVo init = UserLikeListVo.init(userInfo,);
                userUserLikeListVoList.add(userLikeListVo);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        } else {

            for (Long userLike : userLikes) {
                RecommendUser recommendUser = mapRecommendUser.get(userLike);
                UserInfo userInfo = byIds.get(userLike);
                UserLikeListVo init = UserLikeListVo.init(userInfo, recommendUser);
                userUserLikeListVoList.add(init);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        }
    }
    //2.我关注
    private PageResult loveCount(Integer page, Integer pagesize, Integer type) {

        //粉丝  返回我关注id
        List<Long> userLikes = userLikeApi.loveCount(page,pagesize,UserHolder.getUserId());


        //匹配度   分装成map
        Map<Long,RecommendUser> mapRecommendUser = recommendUserApi.loveCount(userLikes,UserHolder.getUserId());

        // List<Long> userLikes, Map<Long, UserInfo> byIds
        //粉丝的userInfo
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userLikes);

        //封装vo
        List<UserLikeListVo> userUserLikeListVoList = new ArrayList<>();

        if (mapRecommendUser == null || mapRecommendUser.size() <=0 ) {
            for (Long userLike : userLikes) {
                UserLikeListVo userLikeListVo = new UserLikeListVo();
                UserInfo userInfo = byIds.get(userLike);
                BeanUtil.copyProperties(userInfo,userLikeListVo);
                userLikeListVo.setMatchRate(30);
                //UserLikeListVo init = UserLikeListVo.init(userInfo,);
                userUserLikeListVoList.add(userLikeListVo);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        } else {

            for (Long userLike : userLikes) {
                RecommendUser recommendUser = mapRecommendUser.get(userLike);
                UserInfo userInfo = byIds.get(userLike);
                UserLikeListVo init = UserLikeListVo.init(userInfo, recommendUser);
                userUserLikeListVoList.add(init);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        }
    }

    //1.互相关注 todo
    private PageResult eachLoveCount(Integer page, Integer pagesize, Integer type) {

        //粉丝  返回互相
        List<Long> userLikes = userLikeApi.eachLoveCount(page,pagesize,UserHolder.getUserId());

        //匹配度   分装成map
        Map<Long,RecommendUser> mapRecommendUser = recommendUserApi.eachLoveCount(userLikes,UserHolder.getUserId());

        // List<Long> userLikes, Map<Long, UserInfo> byIds
        //粉丝的userInfo
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userLikes);

        //封装vo
        List<UserLikeListVo> userUserLikeListVoList = new ArrayList<>();

        if (mapRecommendUser == null || mapRecommendUser.size() <=0 ) {
            for (Long userLike : userLikes) {
                UserLikeListVo userLikeListVo = new UserLikeListVo();
                UserInfo userInfo = byIds.get(userLike);
                BeanUtil.copyProperties(userInfo,userLikeListVo);
                userLikeListVo.setMatchRate(30);

                //UserLikeListVo init = UserLikeListVo.init(userInfo,);
                userUserLikeListVoList.add(userLikeListVo);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        } else {

            for (Long userLike : userLikes) {
                RecommendUser recommendUser = mapRecommendUser.get(userLike);
                UserInfo userInfo = byIds.get(userLike);
                UserLikeListVo init = UserLikeListVo.init(userInfo, recommendUser);
                userUserLikeListVoList.add(init);
            }
            return new PageResult(page, pagesize, 0l, userUserLikeListVoList);
        }

    }



    //4.谁看过我
    public PageResult seeMe(Integer page, Integer pagesize, Integer type) {
        //1.根据UserId查询 list<Visitors>
        Long userId = UserHolder.getUserId();
        List<Visitors> list = visitorsApi.finByfriends(page, pagesize, userId);

        //以防报错 返回空数据
        if (list == null || list.size() <= 0) {
            return new PageResult();
        }

        //2.一个Visitors --> 一个userInfo-->一个 UserLikeListVo
        List<Long> ids = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

        List<UserLikeListVo> vos = new ArrayList<>();

        for (Visitors visitors : list) {

            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            UserLikeListVo vo = UserLikeListVo.init(userInfo, visitors);
            vos.add(vo);

        }
        String key = Constants.VISITORS_USER + userId;
        Long value = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value.toString());
        //3.构建返回值
        return new PageResult(page, pagesize, 0l, vos);
    }
    //粉丝喜欢
    public void fans(Long userLikeId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api保存数据
        userLikeApi.saveLike(userId,userLikeId);
    }
    //取消喜欢
    public void deleteLike(Long likeUserId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api删除数据
        userLikeApi.deleteLike(userId,likeUserId);
    }
}